﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JGSY.Tasks
{
    public static class Thread1
    {
        #region 1、| **Thread * *                | 需要精细控制线程生命周期          | 手动管理，资源开销大  

        public static void Thread001()
        {
            // 创建工作线程
            Woker worker = new Woker();
            Thread workerThread = new Thread(worker.DoWork);
            workerThread.Name = "WorkerThread";

            // 展示线程状态 - Unstarted
            Console.WriteLine("1. 线程状态: " + workerThread.ThreadState);

            // 启动线程 - Running
            Console.WriteLine("2. 启动线程...");
            workerThread.Start();
            Console.WriteLine("   线程状态: " + workerThread.ThreadState);

            // 主线程休眠1秒，让工作线程有机会执行
            Thread.Sleep(1000);

            // 暂停工作线程 - 自定义状态
            Console.WriteLine("3. 暂停线程...");
            worker.Pause();
            Thread.Sleep(500);
            Console.WriteLine("   线程状态: " + workerThread.ThreadState + " (isPaused=" + worker.IsPaused + ")");

            // 恢复工作线程 - 自定义状态
            Console.WriteLine("4. 恢复线程...");
            worker.Resume();
            Thread.Sleep(500);
            Console.WriteLine("   线程状态: " + workerThread.ThreadState + " (isPaused=" + worker.IsPaused + ")");

            // 终止工作线程
            Console.WriteLine("5. 终止线程...");
            worker.Stop();
            workerThread.Join(); // 等待线程结束
            Console.WriteLine("   线程状态: " + workerThread.ThreadState);

            Console.WriteLine("主线程退出");
            Console.WriteLine("主线程退出");
        }
        public class Woker
        {
            private bool _isRunning = true;
            private bool _isPaused = false;
            public bool IsPaused => _isPaused;
            ManualResetEvent resetEvent = new ManualResetEvent(true);
            public void DoWork(object? obj)
            {
                while (_isRunning)
                {
                    // 检查是否需要暂停
                    resetEvent.WaitOne();

                    // 模拟工作
                    Console.WriteLine(Thread.CurrentThread.Name + " is working...");
                    Thread.Sleep(200);
                }
            }
            /// <summary>
            /// resetEvent
            /// </summary>
            public void Pause()
            {
                _isPaused = true;
                resetEvent.Reset();
            }
            public void Resume()
            {
                _isPaused = false;
                resetEvent.Set();
            }

            public void Stop()
            {
                _isRunning = false;
                Resume(); // 确保线程可以退出
            }


        }
        #endregion
    }
}
